package com.example.captchademo2.demos.web.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ICaptcha;
import com.example.captchademo2.demos.web.model.CaptchaProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author Q
 * @create 2025-06-03-16:45
 */
@RequestMapping("/captcha")
@RestController
public class CaptchaController {
    private static long VALID_TIME = 60*1000;
    @Autowired
    private CaptchaProperties captchaProperties;
    @RequestMapping("/get")
    public void getCaptcha(HttpSession session, HttpServletResponse response) throws IOException {
        ICaptcha iCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.height);
        iCaptcha.write(response.getOutputStream());
        //禁止缓存
        response.setHeader("Prama", "No-cache");
        //设置返回的格式
        response.setContentType("image/jpeg");
        //打印验证码
        System.out.println(iCaptcha.getCode());
        //存储Session
        session.setAttribute(captchaProperties.getSession().getCode(), iCaptcha.getCode());
        session.setAttribute(captchaProperties.getSession().getDate(), System.currentTimeMillis());
        response.getOutputStream().close();
    }
    //检查验证码
    @RequestMapping("/check")
    public Boolean check(String captchaCode,HttpSession session){

        System.out.println("接收captchaCode:"+captchaCode);
        //参数校验
        //判断用户输入的验证码是否和session中存储的一致
        //是否在有效期内
        if (!StringUtils.hasLength(captchaCode)){
            return false;
        }
        String sessionCode = (String)session.getAttribute(captchaProperties.getSession().getCode());
        Long sessionDate = (Long)session.getAttribute(captchaProperties.getSession().getDate());
        if (captchaCode.equalsIgnoreCase(sessionCode)
                && sessionDate!=null
                && (System.currentTimeMillis() - sessionDate) < VALID_TIME){
            return true;
        }
        return false;
    }
}
